package client

import (
	"gitee.com/it-wind/simple_http"
	"io"
	"log"
	"net"
	"time"
)

type TcpConn struct {
	*simple_http.Router
	net.Conn
	address string
	actions []func(io.Writer)
}

func (c *TcpConn) ReConn() {
	c.Conn = NewConn(c.address)
}

func (c *TcpConn) RegisterAction(f func(io.Writer)) {
	c.actions = append(c.actions, f)
}

func (c *TcpConn) runActions() {
	for i := range c.actions {
		go (c.actions[i])(c.Conn)
	}
}

func (c *TcpConn) Run() {
	c.runActions()
	for {
		err := simple_http.AcceptRequest(c.Conn, c.Router)
		if err != nil {
			log.Println(err.Error())
			c.ReConn()
			c.runActions()
		}
	}
}

func NewConn(addr string) net.Conn {
	for {
		conn, err := net.Dial("tcp", addr)
		if err == nil {
			return conn
		}
		time.Sleep(time.Second)
	}
}

func NewTcpConn(addr string) *TcpConn {
	return &TcpConn{
		Conn:    NewConn(addr),
		address: addr,
		Router:  simple_http.NewRouter(),
		actions: *new([]func(io.Writer)),
	}
}
